﻿using System;
using System.Globalization;

namespace Ewk.Runtime.Serialization.PositionBased
{
    class PositionBasedInt32Serializer : DatafieldSerializer<PositionBasedDatafieldAttribute>
    {
        public override string Serialize(object datafield, PositionBasedDatafieldAttribute datafieldAttribute)
        {
            var value = (int)datafield;
            if (value == default(int))
            {
                return new string(datafieldAttribute.DefaultCharacter, datafieldAttribute.Length);
            }

            if (datafieldAttribute.DefaultCharacter == '0' && string.IsNullOrEmpty(datafieldAttribute.Format))
            {
                var format = string.Format(
                    CultureInfo.CurrentCulture, "{0};-{1};{2}",
                    new string(datafieldAttribute.DefaultCharacter, datafieldAttribute.Length),
                    new string(datafieldAttribute.DefaultCharacter, datafieldAttribute.Length - 1),
                    new string(datafieldAttribute.DefaultCharacter, datafieldAttribute.Length));

                datafieldAttribute.Format = format;
            }

            return value.ToString(datafieldAttribute.Format, CultureInfo.CurrentCulture);
        }

        public override object Deserialize(string datafield, PositionBasedDatafieldAttribute datafieldAttribute)
        {
            if (string.IsNullOrEmpty(datafield))
            {
                return default(int);
            }

            int result;
            if (int.TryParse(datafield, out result))
            {
                return result;
            }

            var exceptionMessage = string.Format(CultureInfo.CurrentCulture, ExceptionMessages.CannotDeserializeValue, datafield, DatafieldType);
            OnDatafieldSerializationFailed(exceptionMessage);

            return default(int);
        }

        public override Type DatafieldType
        {
            get { return typeof(int); }
        }
    }
}
